package com.cgnpc.scp.sri.budget.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.CreateFileInfo;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.service.AppConstantService;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.run.utils.CommonExportUtil;
import com.cgnpc.scp.sri.budget.mybatis.entity.BudgetInfo;
import com.cgnpc.scp.sri.budget.mybatis.entity.BudgetItem;
import com.cgnpc.scp.sri.budget.mybatis.mapper.client.BudgetInfoMapper;
import com.cgnpc.scp.sri.budget.pojo.BudgetInfoVo;
import com.cgnpc.scp.sri.budget.pojo.Expense;
import com.cgnpc.scp.sri.budget.service.BudgetInfoService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("budgetInfoService")
public class BudgetInfoServiceImpl implements BudgetInfoService {
    private final static Logger LOGGER = LoggerFactory.getLogger(BudgetInfoServiceImpl.class);
    @Autowired
    private BudgetInfoMapper budgetInfoMapper;

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private AppConstantService appConstantService;

    @Autowired
    private SqlSession sqlSession;

    @Override
    public MyPageResult<BudgetInfo> queryListPage(Map<String, Object> params) {
        MyPageResult<BudgetInfo> re = null;
        int pageNum = 1;
        int pageSize = 10;
        try {
            pageNum = Integer.parseInt(params.get("pageNum") + "");
            pageSize = Integer.parseInt(params.get("pageSize") + "");
        }catch (Exception e){
            e.printStackTrace();
        }
        Page<BudgetInfo> queryPage = PageHelper.startPage(pageNum, pageSize);
        budgetInfoMapper.listPage(params);
        PageInfo<BudgetInfo> pageResult = new PageInfo<>(queryPage.getResult());
        re = MyPageResultUtil.createMyPageResult(pageResult);

        return re;
    }

    @Override
    public List<String> getAllYear() {
        return budgetInfoMapper.getAllYear();
    }

    @Override
    public AjaxResult save(BudgetInfo budgetInfo) {
        List<BudgetInfo> budgetInfos = budgetInfoMapper.selectList(new QueryWrapper<BudgetInfo>()
        .select("*",
                "(travel_expense + meeting_expense + consulting_expense + business_support_expense + device_expense + software_expense) as total_expense")
        .eq("year", budgetInfo.getYear()));
        if(budgetInfos != null && budgetInfos.size() > 0){
            return AjaxResult.error("所填写年份已存在预算记录，请重新填写新的年份");
        }

        budgetInfo.setId(IDHelper.uuid());
        budgetInfo.setCreateUser(currentUser.getCurrentUserDetail().getUserId());
        budgetInfo.setLastUpdateUser(currentUser.getCurrentUserDetail().getUserId());
        budgetInfo.setCreateUserName(currentUser.getCurrentUserDetail().getUserName());
        budgetInfo.setLastUpdateUserName(currentUser.getCurrentUserDetail().getUserName());
        budgetInfo.setLastUpdateTime(new Date());
        budgetInfo.setCreateTime(new Date());
        budgetInfoMapper.insert(budgetInfo);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult update(BudgetInfo budgetInfo) {
        budgetInfo.setLastUpdateUser(currentUser.getCurrentUserDetail().getUserId());
        budgetInfo.setLastUpdateUserName(currentUser.getCurrentUserDetail().getUserName());
        budgetInfo.setLastUpdateTime(new Date());
        budgetInfoMapper.updateById(budgetInfo);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult budgetInfo(String id) {
        BudgetInfoVo vo = new BudgetInfoVo();
        List<BudgetInfo> budgetInfos = budgetInfoMapper.selectList(new QueryWrapper<BudgetInfo>()
                .select("*",
                        "(travel_expense + meeting_expense + consulting_expense + business_support_expense + device_expense + software_expense) as total_expense")
                .eq("id", id));
        if(budgetInfos == null || budgetInfos.size() == 0){
            return AjaxResult.success();
        }
        BudgetInfo info = budgetInfos.get(0);
        vo.setBudgetInfo(info);
        String year = info.getYear();
        vo.setUsed(getUsedByYear(year));
        vo.setLeft(getLeftByYear(year));

        return AjaxResult.success().put("data", vo);
    }

    public Expense getUsedByYear(String year){
        List<Expense> usedList = budgetInfoMapper.getAllItemByYear(year);
        if(usedList != null && usedList.size() != 0) {
            return usedList.get(0);
        }
        return null;
    }

    @Override
    public Expense getLeftByYear(String year){
        Expense left = new Expense();
        List<BudgetInfo> infos = budgetInfoMapper.selectList(new QueryWrapper<BudgetInfo>()
                .select("*",
                        "(travel_expense + meeting_expense + consulting_expense + business_support_expense + device_expense + software_expense) as total_expense")
                .eq("year", year));
        if(infos == null || infos.size() == 0){
            return left;
        }
        BudgetInfo info = infos.get(0);
        List<Expense> usedList = budgetInfoMapper.getAllItemByYear(year);
        if(usedList != null && usedList.size() != 0) {
            Expense used = usedList.get(0);

            left.setTravelExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getTravelExpense()) ? "0":info.getTravelExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getTravelExpense()) ? "0":used.getTravelExpense())) +"");
            left.setBusinessSupportExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getBusinessSupportExpense()) ? "0":info.getBusinessSupportExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getBusinessSupportExpense()) ? "0":used.getBusinessSupportExpense())) +"");
            left.setConsultingExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getConsultingExpense()) ? "0":info.getConsultingExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getConsultingExpense()) ? "0":used.getConsultingExpense())) +"");
            left.setDeviceExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getDeviceExpense()) ? "0":info.getDeviceExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getDeviceExpense()) ? "0":used.getDeviceExpense())) +"");
            left.setMeetingExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getMeetingExpense()) ? "0":info.getMeetingExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getMeetingExpense()) ? "0":used.getMeetingExpense())) +"");
            left.setSoftwareExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getSoftwareExpense()) ? "0":info.getSoftwareExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getSoftwareExpense()) ? "0":used.getSoftwareExpense())) +"");
            left.setTotalExpense((Double.parseDouble(StringUtil.isNullOrSpace(info.getTotalExpense()) ? "0":info.getTotalExpense()) - Double.parseDouble(StringUtil.isNullOrSpace(used.getTotalExpense()) ? "0":used.getTotalExpense())) +"");
            return left;
        }
        return left;
    }
    @Override
    public CreateFileInfo exportExcel(Map<String, Object> params) throws Exception {
        final String logInfo = "[exportExcel_UUID_" + UUID.randomUUID() + "]";
        CreateFileInfo createFileInfo = null;

        try {
            List<String> titleList = Arrays.asList(
                    "预算年度","差旅费","会议费","咨询费","业务支持费"
                    ,"设备费","软件费","申请总额"
            );
            List<String> fields = Arrays.asList("year","travelExpense","meetingExpense","consultingExpense","businessSupportExpense"
                    ,"deviceExpense","softwareExpense","totalExpense"
            );

            CommonExportUtil<BudgetInfo> util = new CommonExportUtil<>();
            createFileInfo = util.exportExcel(appConstantService, sqlSession, titleList, fields
                    , "com.cgnpc.scp.sri.budget.mybatis.mapper.client.BudgetInfoMapper"
                    ,"listPageExport", params);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return createFileInfo;
    }
}
